/*
 * Copyright (c) 2024 Hunan OpenValley Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ota_event/ota_event.h"
#include "log/log.h"
#include <iostream>
#include <string>
#include <cstdint>
#include "slot_info/slot_info.h"
#ifdef UPDATER_AB_SUPPORT
#include "partitionslot_manager.h"
#endif

#ifdef UPDATER_AB_SUPPORT
enum ReturnSetOtaStatus {
    SET_OTA_STATUS_FAILED = -1, // Failed to call SetOTAStatus to set information.
    BOOT_SUCCESS_IN_OTA = 0,    // In the ota stage, startup is complete.
    BOOT_SUCCESS_IN_NORMAL = 1, // In the non-ota stage, startup is complete.
    BOOT_FAILD_IN_OTA = 2,      // In the ota stage, startup is failed.
    BOOT_FAILD_IN_NORMAL = 3,   // In the non-ota stage, startup is failed.
};
int SetOTAStatus(int status)
{
    OHOS::HDI::Partitionslot::V1_1::PartitionSlotManager psMgr;
    int32_t checkpoint = -1;

    int32_t retGetcheckpoint = psMgr.GetCheckpoint(checkpoint);
    if (retGetcheckpoint != 0 || checkpoint  == -1) {
        return SET_OTA_STATUS_FAILED;
    }
    // In the ota stage, startup is failed
    if (status == 0 && checkpoint == 1) {
        // switch partition
        Updater::SetActiveSlot();
        // Write checkpoint=0 to prevent remounting the data partition the next time it is accessed
        // Upgrade fails, reboot to do userdata rollback
        int retSetcheckpoint = psMgr.SetCheckpoint(0);
        if (retSetcheckpoint != 0) {
            return SET_OTA_STATUS_FAILED;
        }
        return BOOT_FAILD_IN_OTA;
    // In the ota stage, startup is complete.
    } else if (status == 1 && checkpoint == 1) {
        // Write checkpoint=0 to prevent remounting the data partition the next time it is accessed
        int retSetcheckpoint = psMgr.SetCheckpoint(0);
        if (retSetcheckpoint != 0) {
            return SET_OTA_STATUS_FAILED;
        }
        return BOOT_SUCCESS_IN_OTA;
    // In the non-ota stage, startup is complete
    } else if (status == 1 && checkpoint == 0) {
        return BOOT_SUCCESS_IN_NORMAL;
    // In the non-ota stage, startup is failed
    } else if (status == 0 && checkpoint == 0) {
        return BOOT_FAILD_IN_NORMAL;
    }
    return SET_OTA_STATUS_FAILED;
}
#endif